package com.sgq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sgq.entity.Role;
import com.sgq.dao.RoleMapper;
import com.sgq.entity.User;
import com.sgq.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgq.vo.RoleQueryVo;
import com.sgq.vo.UserQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sgq
 * @since 2024-09-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public IPage<Role> findPage(RoleQueryVo roleQueryVo) {
        //传递一个page对象 =》 当前页  数据条数大小
        System.out.println("roleQueryVo = " + roleQueryVo);
        Long pageNum = roleQueryVo.getPageNum();
        Long pageSize = roleQueryVo.getPageSize();
        IPage<Role> page = new Page<>(pageNum,pageSize);
        //条件按名字
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        //判断条件是否为空 "username"
        queryWrapper.like(!ObjectUtils.isEmpty(roleQueryVo.getRoleName()), Role::getRoleName, roleQueryVo.getRoleName());

        IPage<Role> iPage = this.baseMapper.selectPage(page, queryWrapper);
        return iPage;
    }


    @Override
    @Transactional
    public boolean removeRoleAndRelationship(Long roleId) {
        //删除当前角色
        int count = this.baseMapper.deleteById(roleId);
        //删除角色所有的映射权限关系
        this.baseMapper.deleteRolePermission(roleId);

        return count == 1 ? true : false;
    }

    @Override
    @Transactional
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        //删除该角色对应的权限信息
        baseMapper.deleteRolePermission(roleId);
        //保存角色权限
        if (permissionIds.size() > 0) {
          int count = baseMapper.saveRolePermission(roleId, permissionIds);
          return  count == permissionIds.size();
        }
        return true;
    }
}
